/**
 * @author yinyuejia
 * @file 用户相关
 */

import storage from '@/utils/storage';
// import cookieUtil from '@/utils/cookie';
import Cookie from 'js-cookie';
import loadsh from 'lodash';

const AES = require('crypto-js/aes'); // 加密解密
const EncUtf8 = require('crypto-js/enc-utf8'); // 编码规则

const defaultState = {
  token: '',
  permissions: [],
  rememberme: {},
  info: {},
  roles: [],
};
const DEFAULTSTATE: any = loadsh.cloneDeep(defaultState);
const storageKey = 'user';
const SECRETKEY = 'Vue-Element-Faster@2022';
export default {
  state: defaultState,
  mutations: {
    reloadUser(state: any) {
      const data = storage.get(storageKey);
      if (data) {
        Object.keys(data).forEach((k) => {
          state[k] = data[k];
        });
      }
      state.token = Cookie.get('ACCESS_TOKEN');
      // 如果已经记住密码了，解密出来密码赋值表单
      const remembermeData = Cookie.get('rememberme');
      if (remembermeData) {
        const obj = JSON.parse(AES.decrypt(remembermeData, SECRETKEY).toString(EncUtf8));
        state.rememberme = {
          username: obj.username,
          password: obj.password,
        };
      }
    },
    clear(state: any) {
      Object.keys(DEFAULTSTATE).forEach((k) => {
        state[k] = loadsh.cloneDeep(DEFAULTSTATE[k]);
      });
      storage.clear(storageKey);
      Cookie.remove('ACCESS_TOKEN');
    },
    // 登录后存token
    setToken(state: any, payload: any) {
      state.token = payload.token;
      Cookie.set('ACCESS_TOKEN', payload.token);
    },
    // 登录后存权限
    setPermissions(state: any, payload: any) {
      state.permissions = payload.permissions;
      storage.set(`${storageKey}.permissions`, state.permissions);
    },
    setRoles(state: any, payload: any) {
      state.roles = payload.roles;
      storage.set(`${storageKey}.roles`, state.roles);
    },
    // 登录后存用户
    setUser(state: any, payload: any) {
      state.info = payload.info;
      storage.set(`${storageKey}.info`, state.info);
    },
    // 看看是不是要记住密码
    setRememberme(state: any, payload: any) {
      if (payload.rememberme) {
        state.rememberme = {
          username: payload.username,
          password: payload.password,
        };
        // 加密存储
        const data = AES.encrypt(JSON.stringify(state.rememberme), SECRETKEY).toString();
        Cookie.set('rememberme', data, { expires: 90 * 24 * 60 * 60 });
      } else {
        state.rememberme = {};
        Cookie.remove('rememberme');
      }
    },
  },
  getters: {
    // 判断是否登录
    isLogin(state: any) {
      return Object.keys(state.info).length > 0;
    },
  },
};
